package com.sphd.education.activitys;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.sphd.education.EducationApplication;
import com.sphd.education.R;
import com.sphd.education.base.BaseActivity;
import com.sphd.education.info.ClassifyTwo;
import com.sphd.education.info.EducationIntentKey;
import com.sphd.education.info.MyInfo;
import com.sphd.education.info.PushInfo;
import com.sphd.education.modle.EducationUrl;
import com.sphd.education.utils.MD5keyBean;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
 * 登陆界面
 * */
public class LoginActivity extends BaseActivity {

    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.username)
    EditText username;
    @Bind(R.id.usernameWrapper)
    TextInputLayout usernameWrapper;
    @Bind(R.id.password)
    EditText password;
    @Bind(R.id.passwordWrapper)
    TextInputLayout passwordWrapper;
    @Bind(R.id.lonin_button)
    Button loninButton;
    @Bind(R.id.forget_pwd)
    TextView forPwd;
    @Bind(R.id.remeberpassword)
    CheckBox remeberpassword;
    private Intent intent;
    private Context context;
    private MyInfo myInfo;//我的实体类存储设置的相关信息
    private PushInfo pushInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        initView();
    }

    @Override
    public void initView() {
        intent = new Intent();
        context = LoginActivity.this;
        myInfo = DataSupport.findLast(MyInfo.class);
        if (myInfo == null) {
            myInfo = new MyInfo();
            myInfo.setUsername(username.getText().toString().trim());
            myInfo.setUserpassword(password.getText().toString().trim());
            myInfo.setLogon_status(0);
            myInfo.setRememberpassword(remeberpassword.isChecked());
            myInfo.save();
        } else {
            if (myInfo.isRememberpassword()) {
                if (!TextUtils.isEmpty(myInfo.getUsername())) {
                    username.setText(myInfo.getUsername());
                    password.setText(myInfo.getUserpassword());
                }
                remeberpassword.setChecked(true);

            } else {
                remeberpassword.setChecked(false);
            }
        }
        pushInfo = DataSupport.findLast(PushInfo.class);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(EducationIntentKey.LOGONCODE, intent);
                finish();//这是自带的箭头的返回的监听
            }
        });
        forPwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString(EducationIntentKey.FLAG, "forget");
                intent.putExtra("minefragment", bundle);//需修改统一字段
                startActivity(intent);
            }
        });
    }

    @Override
    public void findViewById() {

    }

    @Override
    public void myNet() {

        StringRequest stringRequest = new StringRequest(Request.Method.POST,
                EducationUrl.HttpTitle + EducationUrl.LogonUser, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
//                1:noName 不存在的用户名
//                2: errorPwd密码错误
//                3:success 登陆成功

                switch (response) {
                    case "errorPwd":
                        EducationUrl.showToast(context, "密码错误");
                        break;
                    case "noName":
                        EducationUrl.showToast(context, "不存在的用户名");
                        break;
                    default:
                        EducationUrl.showLog(response);
                        saveMyinfo(response);
                        EducationUrl.showToast(context, "登陆成功");
                        setResult(EducationIntentKey.LOGONCODE, intent);
                        finish();
                        break;
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                EducationUrl.showToast(context, error.toString());
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("mobile", username.getText().toString());
                map.put("password", new MD5keyBean().getkeyBeanofStr(password.getText().toString()));
                if (pushInfo.getChannelId() != null) {
                    map.put("channelID", pushInfo.getChannelId());
                }
                Log.e("m22m",EducationUrl.HttpTitle + EducationUrl.LogonUser);
                Log.e("mm",map.toString());
                EducationUrl.showLog("channelID", "pushInfo.getChannelId()=" + pushInfo.getChannelId());
                return map;
            }
        };
        stringRequest.setTag("logon");
        EducationApplication.getRequestQueue().add(stringRequest);
        EducationApplication.getRequestQueue().start();
    }

    @OnClick(R.id.lonin_button)
    public void setOnClickLoninButton() {
        myNet();
    }
    @OnClick(R.id.go_register)
    public void gotoRegister() {
        intent.setClass(context, RegisterActivity.class);
        Bundle bundle =new Bundle();
        bundle.putSerializable("myinfo", myInfo);
        bundle.putString(EducationIntentKey.FLAG,"register");
        intent.putExtra("minefragment", bundle);//需修改统一字段
        startActivity(intent);
//        startActivityForResult(intent, EducationIntentKey.REGISTERCODE);
    }

    private void saveMyinfo(String result) {
        EducationUrl.showLog("logon", "" + result);
        try {
            ContentValues values = new ContentValues();
            JSONObject jsonObject = new JSONObject(result);
            if (remeberpassword.isChecked()) {
                values.put("userpassword", password.getText().toString());
                values.put("rememberpassword", remeberpassword.isChecked());
            } else {

                values.put("userpassword", "");
                values.put("rememberpassword", remeberpassword.isChecked());
            }
            values.put("name", jsonObject.getString("name"));
//            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//            Date dbDate = (Date) dateFormat.parse(jsonObject.getString("birthday").trim());
//            String strDate=dateFormat.format(dbDate);
            values.put("birthday",jsonObject.getString("birthday"));
            values.put("userid", jsonObject.getString("id"));
            values.put("username", jsonObject.getString("mobile"));
            values.put("name", jsonObject.getString("realName"));
            values.put("gender", jsonObject.getString("gender"));
            values.put("description", jsonObject.getString("description"));
//            values.put("age",jsonObject.getString("age"));
            if (jsonObject.has("likes")) {
                values.put("likes", jsonObject.getString("likes"));
            }
            values.put("userimgurl", jsonObject.getString("avatar"));
            values.put("logon_status", 1);
            values.put("id", 1);
            DataSupport.update(MyInfo.class, values, myInfo.getId());
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            setResult(EducationIntentKey.LOGONCODE, intent);
            finish();//这是自带的箭头的返回的监听
            //do something...
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }
}
